package com.butterfly.mvc.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by DouDou on 2016/9/19.
 */
public class MvcParser {

    public MvcParser(){

    }

    public static Map parseXml(String xmlPath) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File(xmlPath));
        Element root = document.getRootElement();
        Element scan = root.element("scan");

        /**分析扫描路径**/
        Map<String,String> rstMap= new HashMap<String,String>();
        rstMap.put("scanPath",scan.attributeValue("scanPath"));

        /**分析配置项**/
        Element configs = root.element("configs");
        List<Element> configArr = configs.elements();
        for(Iterator<Element> it= configArr.iterator();it.hasNext();){
            Element e = it.next();
            String configName = e.attributeValue("param");
            List<Element> items = e.elements();
            if("page".equals(configName)) {
                for (Iterator<Element> i = items.iterator(); i.hasNext(); ) {
                    Element item = i.next();
                    String name = item.attributeValue("name");
                    name = "page"+(name.charAt(0) + "").toUpperCase()+name.substring(1);
                    rstMap.put(name,item.attributeValue("value"));
                }
            }
            if("redirct".equals(configName)) {
                for (Iterator<Element> i = items.iterator(); i.hasNext(); ) {
                    Element item = i.next();
                    String name = item.attributeValue("name");
                    name = "redirct"+(name.charAt(0) + "").toUpperCase()+name.substring(1);
                    rstMap.put(name,item.attributeValue("value"));
                }
            }

        }

        for(Iterator<String> it = rstMap.keySet().iterator();it.hasNext();){
            String e = it.next();
            System.out.println(e +":"+rstMap.get(e));
        }
        return rstMap;
    }

    public static void main(String args[]){
        try {
            MvcParser.parseXml("D:\\liuchunlin\\work\\idea\\annotationmvc\\src\\main\\resources\\mvc\\mvc-config.xml");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
